<?php

/**
 * Author：晴天 QQ：1186258278
 * Creation：2020/4/24 0:19
 * Filename：Api.php
 * api下单模块，还需api控制订单！
 */

namespace lib\supply;


use extend\GoodsImage;
use lib\Hook\Hook;
use Medoo\DB\SQL;

class Api
{
    /**
     * @param $OrData 订单数据
     * @param $Goods GoodsImage;
     */
    public static function Submit($OrData, $Goods)
    {
        global $date;
        $DB = SQL::DB();

        $PostArr = [];
        $Url = html_entity_decode($Goods['curl']);
        $Post = html_entity_decode($Goods['post_data']);
        $Order = $DB->get('order', '*', ['id' => $OrData['id']]);
        $InputData = json_decode($Order['input'], TRUE);
        if ($Goods['specification'] == 2 && $Goods['specification_type'] == 2) {
            $InputData = RuleSubmitParameters(json_decode($Goods['specification_sku'], TRUE)[0], $InputData);
        }
        $Url = str_replace('[name]', $Goods['name'], $Url);
        $Url = str_replace('[num]', ($Goods['num'] * $Goods['quantity']), $Url);
        $Url = str_replace('[date]', $date, $Url);
        $Url = str_replace('[order]', $Order['order'], $Url);
        $Url = str_replace('[price]', $Order['price'], $Url);
        $Url = str_replace('[time]', time(), $Url);
        $Url = str_replace('[url]', href(), $Url);
        for ($i = 0; $i < count($InputData); $i++) {
            $Url = str_replace('[input' . ($i + 1) . ']', $InputData[$i], $Url);
        }

        if ($Post <> '') {
            $Post = str_replace('[num]', ($Goods['num'] * $Goods['quantity']), $Post);
            $Post = str_replace('[date]', $date, $Post);
            $Post = str_replace('[order]', $Order['order'], $Post);
            $Post = str_replace('[price]', $Order['price'], $Post);
            $Post = str_replace('[time]', time(), $Post);
            $Post = str_replace('[url]', href(), $Post);
            for ($i = 0; $i < count($InputData); $i++) {
                $Post = str_replace('[input' . ($i + 1) . ']', $InputData[$i], $Post);
            }
            parse_str($Post, $PostArr);
            $PostData = [];
            foreach ($PostArr as $key => $value) {
                $key = str_replace(['?', '&'], '', $key);
                $PostData = array_merge($PostData, [$key => $value]);
            }
            $PostArr = $PostData;
        }

        $DataHook = [
            $Url => $PostArr,
            'Order' => $OrData
        ];

        Hook::execute('ApiSubmit', $DataHook);

        $CurlData = self::SuppluCurl($Url, $PostArr);
        if ($CurlData == '') {
            return false;
        } else $CurlData = json_decode($CurlData, TRUE);

        $DataHook = [
            $Url => $CurlData,
            'Order' => $OrData
        ];

        Hook::execute('ApiFinish', $DataHook);

        unset($DataHook);

        /**
         * 遍历匹配自定义状态参数
         */
        foreach (explode('|', $Goods['goods_url']) as $value) {
            if (isset($CurlData[$value])) {
                $code = $CurlData[$value];
            }
        }

        /**
         * 遍历匹配自定义内容参数
         */
        foreach (explode('|', $Goods['goods_mainKey']) as $value) {
            if (isset($CurlData[$value])) {
                $msg = $CurlData[$value];
            }
        }

        if (isset($CurlData['msg'])) {
            $msg = $CurlData['msg'];
        }

        if (isset($CurlData['message'])) {
            $msg = $CurlData['message'];
        }

        if (isset($CurlData['code'])) {
            $code = $CurlData['code'];
        }

        if (isset($CurlData['status'])) {
            $code = $CurlData['status'];
        }

        if (isset($CurlData['money'])) {
            $money = $CurlData['money'];
        }

        if (isset($CurlData['order'])) {
            $orders = $CurlData['order'];
        }

        if (!isset($msg)) {
            $msg = '未知返回信息' . json_encode($CurlData, JSON_UNESCAPED_UNICODE);
        }

        if (!isset($code)) {
            $code = -1;
        }

        if (!isset($money)) {
            $money = 0;
        }

        if (!isset($orders)) {
            $orders = -1;
        }

        if ($code < 0) {
            $DB->update('order', [
                'return' => $msg
            ], [
                'id' => $OrData['id']
            ]);
        }

        return [
            'code' => $code,
            'msg' => $msg,
            'money' => $money,
            'order' => $orders
        ];
    }


    /**
     * @param $url URL链接
     * @param int $post Post数据
     * @param int $referer 伪造来路域名
     * @param int $cookie CK数据
     * @param int $header 开启请求头
     * @param int $ua 环境模拟
     * @param int $nobaody 输出请求头信息
     * @return bool|string
     * 对接提交专用,此处提交的数据都会被记录！
     */
    public static function SuppluCurl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
    {
        global $accredit, $date;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $httpheader[] = "Accept: */*";
        $httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
        $httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
        $httpheader[] = "Connection: close";
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        if ($header) {
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
        }
        if ($cookie) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        if ($referer) {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
        if ($ua) {
            curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        } else {
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
        }
        if ($nobaody) {
            curl_setopt($ch, CURLOPT_NOBODY, 1);
        }
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
        mkdirs(ROOT . '/includes/extend/log/Supply/');
        @file_put_contents(ROOT . '/includes/extend/log/Supply/Supply_' . $accredit['token'] . '.log', json_encode([$date => ['url' => $url, 'post' => $post, 'data' => $ret]], JSON_UNESCAPED_UNICODE) . 'SEGMENTATION', FILE_APPEND);
        curl_close($ch);
        return $ret;
    }

    /**
     * @param $url URL链接
     * @param int $post Post数据
     * @param int $referer 伪造来路域名
     * @param int $cookie CK数据
     * @param int $header 开启请求头
     * @param int $ua 环境模拟
     * @param int $nobaody 输出请求头信息
     * @return bool|string
     * 商品对接专用,此处不会被记录
     */
    public static function Curl($url, $post = 0, $referer = 0, $cookie = 0, $header = 0, $ua = 0, $nobaody = 0)
    {
        global $accredit, $date;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $httpheader[] = "Accept: */*";
        $httpheader[] = "Accept-Encoding: gzip,deflate,sdch";
        $httpheader[] = "Accept-Language: zh-CN,zh;q=0.8";
        $httpheader[] = "Connection: close";
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        if ($post) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
        if ($header) {
            curl_setopt($ch, CURLOPT_HEADER, TRUE);
        }
        if ($cookie) {
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        if ($referer) {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }
        if ($ua) {
            curl_setopt($ch, CURLOPT_USERAGENT, $ua);
        } else {
            curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36');
        }
        if ($nobaody) {
            curl_setopt($ch, CURLOPT_NOBODY, 1);
        }
        curl_setopt($ch, CURLOPT_ENCODING, "gzip");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ret = curl_exec($ch);
        curl_close($ch);
        return $ret;
    }
}
